import {
  createRouter,
  createWebHashHistory
} from 'vue-router'

import store from '@/store'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [{
    path: '/login',
    component: () => import('@/views/login.vue'),
    beforeEnter: (to, from, next) => {
      if (store.getters.user) {
        next('/')
      }
      next();
    }
  }]
});

// 所有的页面
let operationPages = {};
operationPages = Object.assign(operationPages, import.meta.glob("../views/operation/**/**.vue"));
let financePages = {};
financePages = Object.assign(financePages, import.meta.glob("../views/finance/**/**.vue"));

// 不需要登录就能访问的页面
const annoUrls = ['/login'];

// 是否添加过路由
let addRouterFlag = false;

let user = null;

// 运营页面
let operationAddRouters = {
  path: '/operation',
  component: () => import('@/views/operation/layout.vue'),
  children: []
}

// 财务页面
let financeAddRouters = {
  path: '/finance',
  component: () => import('@/views/finance/layout.vue'),
  children: []
}

// 要添加的路由
let addRouters = {
  path: '/',
  component: () => import('@/views/layout.vue'),
  children: [
    operationAddRouters,
    financeAddRouters
  ]
}

addRouters.redirect = addRouters.children[0].path;

router.beforeEach((to, from, next) => {
  if (annoUrls.indexOf(to.path) != -1) {
    next();
    return;
  }
  user = store.getters.user;
  if (!user) {
    next('/login');
    return;
  } else {
    if (!addRouterFlag) {
      addRouterFlag = true;
      operationAddRouters.children = createNewRouter(user.operationRouterList);
      financeAddRouters.children = createNewRouter(user.financeRouterList);
      // operationAddRouters.children = createNewRouter(user.sysRouterList);
      // addRouters.children.push({
      //   path: '/update-pwd',
      //   name: 'updatePwd',
      //   meta: {
      //     name: '修改密码',
      //     hide: true
      //   },
      //   component: resolve => require(['/src/views/layout/update-pwd'], resolve)
      // });
      if (operationAddRouters.children.length) {
        operationAddRouters.redirect = operationAddRouters.children[0].path;
      }
      if (financeAddRouters.children.length) {
        financeAddRouters.redirect = financeAddRouters.children[0].path;
      }
      router.addRoute(addRouters);
      router.addRoute({
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('/src/views/404.vue')
      });
      next({
        ...to,
        replace: true
      });
    }
  }
  next();
});

// 创建路由
function createNewRouter(routers, activeMenu) {
  return routers.filter(item => {
    let component = item.component;
    if (!component) return false;
    item.meta = {
      activeMenu: activeMenu || item.path,
      ...item
    }
    item.component = operationPages[`../views/${component}.vue`];
    if (item.children && item.children.length) {
      createRouter(item.children, item.router);
    }
    return true;
  })
}

export default router;